/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ve.usb.cep.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import java.util.Random;


/**
 *
 * @author Andras
 */
public class Hash {

  public static boolean comparePsw(String psw, String hash)
    throws NoSuchAlgorithmException, UnsupportedEncodingException
  {
    String salt = hash.substring(0, 10);
    return calc(psw, salt).equals(hash);
  }
  public static String calcPsw(String psw){ 
    byte[] salt;
    salt = new byte[5];
    new Random().nextBytes(salt);
    try{
        return calc(psw, byteToHex(salt));
    }catch(Exception e){
        return null;
    }
  }

  protected static String calc(String text, String salt)
    throws NoSuchAlgorithmException, UnsupportedEncodingException
  {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] pswHash = md.digest( (salt + text).getBytes("ISO-8859-1") );
    return salt + byteToHex( pswHash );
  }
 
  protected static String byteToHex(byte[] data){
    StringBuilder result = new StringBuilder();
    char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'};
    for (int idx = 0; idx < data.length; ++idx) {
      byte b = data[idx];
      result.append( digits[ (b&0xf0) >> 4 ] );
      result.append( digits[ b&0x0f] );
    }
    return result.toString();
  }
}